<!DOCTYPE html>
<html lang="en" xmlns:th="http://www.thymeleaf.org">
<head>
    <meta charset="UTF-8">
    <title>video</title>
</head>
<body>
<h2 style="text-align: center;">播放页面</h2>
<h3 id="userId" style="text-align: center;"></h3>
<div style="text-align: center;">
    <div>
        <video id="localVideo" class="video" autoplay="autoplay" muted="muted"></video>
        <video id="remoteVideo" class="video" height="500px" muted></video>
    </div>
</div>
</br>
<div style="text-align: center;">
    <button id="callBtn" onclick="requestConnect()">建立连接</button>
    <button id="hangupBtn" onclick="hangupHandle()">断开连接</button>
</div>
</br>
<div style="text-align: center;">
    对方id: <input id="toUserId">
</div>
</body>
</html>
<!-- script src="./adapter-latest.js"></script -->
<script>
    const localVideo = document.querySelector('#localVideo');
    const remoteVideo = document.querySelector('#remoteVideo');

    const callBtn = document.getElementById('callBtn')
    const hangupBtn = document.getElementById('hangupBtn')

    //使用google公开stun服务器
    const config = {
        iceServers: [
            { urls: 'stun:stun.l.google.com:19302' }
        ],
    };

    let peerConnection = new RTCPeerConnection(null);
    let socket, userId, toUserId;
    let localStream, remoteStream;

    //随机生成自己的用户id
    userId = parseInt(Math.random()*10000);
    document.getElementById('userId').innerText = '我的id:' + userId;

    //向服务器请求连接
    function requestConnect() {
        toUserId = document.getElementById('toUserId').value
        if(!toUserId){
            alert('请输入对方id')
            return false
        }else if(!socket){
            alert('请先打开websocket')
            return false
        }else if(toUserId === userId){
            alert('自己不能和自己连接')
            return false
        }
        //准备连接
        startHandle()
            //发送给远端开启请求
            //socket.send(JSON.stringify({ 'userId': userId, 'toUserId': toUserId, 'message': {'type': 'connect'}}))
            socket.send(JSON.stringify({
                'type': 'connect',
                'message': {
                    'userId': userId,
                    'toUserId': toUserId
                }
            }))
    }

    //开启本地的媒体设备
    async function startHandle() {
        // 1.获取本地音视频流
        // 调用 getUserMedia API 获取音视频流
        let constraints = {
            video: true,
            audio: {
                // 设置回音消除
                noiseSuppression: true,
                // 设置降噪
                echoCancellation: true,
            }
        }

        await navigator.mediaDevices.getUserMedia(constraints)
            .then(gotLocalMediaStream)
            .catch((err) => {
                console.log('getUserMedia 错误', err);
            });
        //创建点对点连接对象
        createConnection();
    }

    //创建点对点连接对象
    function createConnection() {
        //peerConnection = new RTCPeerConnection(config);
        //peerConnection = new webkitRTCPeerConnection(null);
        if (localStream) {
            // 视频轨道
            const videoTracks = localStream.getVideoTracks();
            // 音频轨道
            const audioTracks = localStream.getAudioTracks();
            // 判断视频轨道是否有值
            if (videoTracks.length > 0) {
                console.log(`使用的设备为: ${videoTracks[0].label}.`);
            }
            // 判断音频轨道是否有值
            if (audioTracks.length > 0) {
                console.log(`使用的设备为: ${audioTracks[0].label}.`);
            }
            localStream.getTracks().forEach((track) => {
                peerConnection.addTrack(track);
            })
            console.log('本地流加到对等连接成功！');
        }

        // 监听返回的 Candidate
        peerConnection.addEventListener('icecandidate', handleConnection);
        // 监听 ICE 状态变化
        peerConnection.addEventListener('iceconnectionstatechange', handleConnectionChange)
        //拿到流的时候调用
        peerConnection.addEventListener('track', gotRemoteMediaStream);
    }

    // getUserMedia 获得流后，将音视频流展示并保存到 localStream
    function gotLocalMediaStream(mediaStream) {
        localVideo.srcObject = mediaStream;
        localStream = mediaStream;
        callBtn.disabled = false;
    }

    //连接到WebSocket服务器
    function startWebsocket() {
        toUserId = document.getElementById('toUserId').value
        let webSocketUrl = 'wss://' + location.hostname + '/call/' + userId

        //let webSocketUrl = 'wss://192.168.188.111/call/' + userId
        if ('WebSocket' in window) {
            // console.log(1)
            socket = new WebSocket(webSocketUrl);
            console.log(webSocketUrl);
        } else if ('MozWebSocket' in window) {
            // console.log(2)
            socket = new MozWebSocket(webSocketUrl);
        }
        // socket = new SockJS('https://' + location.host + '/call/' + userId);
        //连接成功
        socket.onopen = function (e) {
            console.log('连接服务器成功!')
        };
        //连接关闭
        socket.onclose = function (e) {
            console.log('close')
        };
        //连接出错
        socket.onerror = function (e) {
            console.error(e)
        };
        //连接通信
        socket.onmessage = onmessage
    }
    //连接服务器
    startWebsocket();

    //进行通信
    function onmessage(e) {

        const data = JSON.parse(e.data)
        const message = data.message
        toUserId = message.userId

        switch (data.type) {
            case 'connect':
                if(confirm(toUserId + '请求连接!')){
                    //准备连接
                    startHandle()
                        //socket.send(JSON.stringify({ 'userId': userId, 'toUserId': toUserId, 'message': {'type': 'start'} }));
                        socket.send(JSON.stringify({
                            'type': 'start',
                            'message': {
                                'userId': userId,
                                'toUserId': toUserId
                            }
                        }))
                }
                break;
            case 'start':
                //同意连接之后开始连接
                startConnection()
                break;
            case 'offer':
                peerConnection.setRemoteDescription(new RTCSessionDescription(message.sdp))
                    .then(() => {})
                    .catch((err) => {
                        console.log('local 设置远端描述信息错误', err);
                    });

                peerConnection.createAnswer()
                    .then(function (answer) {
                        peerConnection.setLocalDescription(answer)
                            .then(() => {
                                console.log('设置本地answer成功!');
                            })
                            .catch((err) => {
                        console.error('设置本地answer失败', err);
                            });
                        //socket.send(JSON.stringify({ 'userId': userId, 'toUserId': toUserId, 'message': answer }));
                        socket.send(JSON.stringify({
                            'type': 'answer',
                            'message': {
                                'userId': userId,
                                'toUserId': toUserId,
                                'sdp': answer
                            }
                        }))
                    }).catch(e => {
                    console.error(e)
                    });
                break;
            case 'answer':
                peerConnection.setRemoteDescription(new RTCSessionDescription(message.sdp))
                    .then(() => {
                        console.log('设置remote answer成功!');
                    })
                    .catch((err) => {
                        console.log('设置remote answer错误', err);
                    });
                break;
            case 'icecandidate':
                // 创建 RTCIceCandidate 对象
                let newIceCandidate = new RTCIceCandidate(message.icecandidate);
                // 将本地获得的 Candidate 添加到远端的 RTCPeerConnection 对象中
                peerConnection.addIceCandidate(newIceCandidate)
                    .then(() => {
                        console.log(`addIceCandidate 成功`);
                    })
                    .catch((error) => {
                        console.log(`addIceCandidate 错误:\n` + `${error.toString()}.`);
                    });
                break;
            case 'hangup':
                // 关闭连接并设置为空
                peerConnection.close();
                peerConnection = null;

                hangupBtn.disabled = true;
                callBtn.disabled = false;

                localStream.getTracks().forEach((track) => {
                    track.stop()
                })
            default:
                break;
        }
    }

    //创建sdp准备建立连接
    function startConnection() {
        callBtn.disabled = true;
        hangupBtn.disabled = false;
        //发送offer
        peerConnection.createOffer()
            .then(description => {
                console.log(`本地创建offer返回的sdp:\n${description.sdp}`)
            // 将 offer 保存到本地
                peerConnection.setLocalDescription(description)
                    .then(() => {
                        console.log('local 设置本地描述信息成功');
                        // 本地设置描述并将它发送给远端
                        //socket.send(JSON.stringify({ 'userId': userId, 'toUserId': toUserId, 'message': description }));
                        socket.send(JSON.stringify({
                            'type': 'offer',
                            'message': {
                                'userId': userId,
                                'toUserId': toUserId,
                                'sdp': description
                            }
                        }))
                    }).catch((err) => {
                        console.log('local 设置本地描述信息错误', err)
                    });
            })
            .catch((err) => {
                console.log('createdOffer 错误', err);
            });
    }

    function hangupHandle() {
        // 关闭连接并设置为空
        peerConnection.close();
        peerConnection = null;

        hangupBtn.disabled = true;
        callBtn.disabled = false;

        localStream.getTracks().forEach((track) => {
            track.stop()
        })

        //向服务器发送挂断信号
        socket.send(JSON.stringify({
            'type': 'hangup',
            'message': {
                'userId': userId,
                'toUserId': toUserId
            }
        }))
    }

    // 3.端与端建立连接
    function handleConnection(event) {
        // 获取到触发 icecandidate 事件的 RTCPeerConnection 对象
        // 获取到具体的Candidate
        console.log("handleConnection")
        const peerConnection = event.target;
        const icecandidate = event.candidate;

        if (icecandidate) {
            //socket.send(JSON.stringify({'userId': userId, 'toUserId': toUserId, 'message': {type: 'icecandidate', icecandidate: icecandidate}}));
            socket.send(JSON.stringify({
                'type': 'icecandidate',
                'message': {
                    'userId': userId,
                    'toUserId': toUserId,
                    'icecandidate': icecandidate
                }
            }))
        }
    }

    // 4.显示远端媒体流
    function gotRemoteMediaStream(event) {
        console.log('开始接收远端视频流')

        if (event.streams[0]) {
            remoteVideo.srcObject = event.streams[0];
            remoteStream = event.streams[0];
        }

        playVideo();
        console.log("成功接收远端视频流！！！")
    }

    //监听ice状态变化
    function handleConnectionChange(event) {
        const peerConnection = event.target;
        //console.log('ICE state change event: ', event);
        console.log(`ICE state: ` + `${peerConnection.iceConnectionState}.`);
    }

    function playVideo() {
        const video = document.getElementById("remoteVideo");
        video.play();
    }

</script>
<style>
    .video {
        background-color: black;
        height: 30vh;
    }
</style>